/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

export class Queue<T> {
  private elements: T[];
  private readonly _capacity: number | undefined;

  constructor(capacity?: number) {
    if (capacity !== undefined) {
      this.elements = new Array<T>(capacity);
    }
    this.elements = [];
    this._capacity = capacity;
  }

  public push(element: T): boolean {
    if (this._capacity !== undefined && this.elements.length === this._capacity) {
      return false;
    }
    this.elements.push(element);
    return true;
  }

  public pop(): T | undefined {
    return this.elements.shift();
  }

  public size(): number {
    return this.elements.length;
  }

  public peek(): T | undefined {
    return this.elements[0];
  }

  public clear(): void {
    this.elements = [];
  }

  /**
   * 如果存在则移除
   * @param search
   */
  public remove(search: T): T | undefined {
    if (typeof search === 'string') {
      for (let i = 0; i < this.elements.length; i++) {
        const element: T = this.elements[i];
        if (typeof element === 'string') {
          if (element.indexOf(search) !== -1) {
            this.elements.splice(i, 1);
            return element;
          }
        }
      }
    }
    return undefined;
  }

  public toString(): string {
    return this.elements.toString();
  }
}
